package com.sanpu.kxe.business.card.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sanpu.library.imagechoose.PhotoPreview;
import com.sanpu.kxe.R;
import com.sanpu.kxe.business.card.bean.DefBankOcrOutput;
import com.sanpu.kxe.business.card.bean.DefBankOutput;
import com.sanpu.kxe.business.card.contract.CardConfig;
import com.sanpu.kxe.business.card.contract.UpdateDefBankContract;
import com.sanpu.kxe.business.card.model.CardModel;
import com.sanpu.kxe.business.card.provider.CardOpenProvider;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.module.luban.Luban;
import com.sanpu.kxe.module.luban.OnRenameListener;
import com.sanpu.kxe.rxservice.RxError;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：修改默认结算卡
 * Created by 薛勇军 on 2018/7/25.
 */

public class UpdateDefBankPresenter implements UpdateDefBankContract.Presenter {

    private UpdateDefBankContract.View mView;

    private CompositeSubscription mSubscription;

    private HashMap<String, File> mImageFiles = null;

    private String chkSts = CardConfig.DEFBANK_PASS;


    public UpdateDefBankPresenter(UpdateDefBankContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        mImageFiles = new HashMap<>();
        getDefBankStatus();
    }

    @Override
    public void takePhoto(String photo, int code) {
        ArrayList<String> photoPaths = new ArrayList<>();
        photoPaths.add(photo);
        PhotoPreview.builder()
                .setPhotos(photoPaths)
                .setCurrentItem(0)
                .start((Activity) mView.getContext(), code);
    }

    @Override
    public void onCompress(String filePath, final String reName) {
        try {
            mView.showLoadingDialog(false, "照片压缩处理中...");
            //同步方法请尽量避免在主线程调用以免阻塞主线程
            Observable.just(filePath)
                    .observeOn(Schedulers.io())
                    .map(new Func1<String, List<File>>() {
                        @Override
                        public List<File> call(String filePath) {
                            return luban(filePath, reName);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<File>>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onNext(List<File> files) {
                            if (files != null && files.size()>0) {
                                mImageFiles.put(reName, files.get(0));
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * luban图片压缩
     * @param filePath 图片地址
     * @param reName 重命名
     * @return
     */
    private List<File> luban(String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(mView.getContext())
                    .load(filePath)
                    .ignoreBy(CommonConfig.LUBAN_COMPRESSSIZE)
                    .isNeedDesired(true)
                    .desiredValue(CommonConfig.LUBAN_COMPRESSSIZE)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void removeFile(String fileKey) {
        if (mImageFiles != null && mImageFiles.containsKey(fileKey)) {
            mImageFiles.remove(fileKey);
        }
    }

    @Override
    public void openCertificateHelpActivity(String currentType) {
        IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
        if (provider != null) {
            provider.openCertificateHelpActivity(mView.getContext(), currentType);
        }
    }

    @Override
    public void onCommit() {
        if (mImageFiles.size() < 3) {
            ToastUtil.showTextViewPrompt("缺少有效的证件照");
            return;
        }
        mView.showLoadingDialog(false);
        Subscription subscription = CardModel.getInstance().ocrBankCardAndFaceMatch(mImageFiles)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DefBankOcrOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        if (e instanceof RxError) {
                            RxError rxError = (RxError) e;
                            new GlobalDialog(mView.getContext())
                                    .title("温馨提示")
                                    .content(rxError.getMessage())
                                    .headerIcon(R.drawable.img_fail_result)
                                    .show();
                        }
                    }

                    @Override
                    public void onNext(DefBankOcrOutput ocrOutput) {
                        mView.showOcrBankViewData(ocrOutput, false);
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取结算卡审核状态
     */
    private void getDefBankStatus() {
        mView.showLoadingDialog(false);
        Subscription subscription = CardModel.getInstance().getDefBankStatus()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DefBankOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(DefBankOutput output) {
                        if (output != null) {
                            chkSts = output.getChkSts();
                            if (TextUtils.equals(CardConfig.DEFBANK_AUDIT, chkSts)) {
                                GlobalDialog dialog = new GlobalDialog(mView.getContext())
                                        .title("审核中！")
                                        .content("(后台正在审核，请耐心等待)");
                                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        ((Activity)mView.getContext()).finish();
                                    }
                                });
                                dialog.show();
                            } else {
                                mView.showViewData(output);
                            }
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取网络图片文件
     */
    @Override
    public void getImageFileByNet(String imageUrl, final String fileName) {
        Glide.with(mView.getContext())
                .load(imageUrl)//强制Glide返回一个Bitmap对象
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        if (bitmap != null) {
                            String filePath = FileUtil.compressAndSave(bitmap, fileName);
                            File imageFile = null;
                            if (!TextUtils.isEmpty(filePath)) {
                                imageFile = new File(filePath);
                            }
                            if (imageFile != null && imageFile.exists()) {
                                if (mImageFiles == null) {
                                    mImageFiles = new HashMap<>();
                                }
                                mImageFiles.put(fileName, imageFile);
                            }
                            if (mImageFiles.size() == 3) {
                                mView.dismissLoadingDialog();
                            }
                        }
                    }
                });
    }

    @Override
    public void openOldUpdateDefBankActivity() {
        CardOpenProvider.getInstance().openOldUpdateDefBankActivity(mView.getContext(), true);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
